package com.nio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

/**
 * @author xl-9527
 * @since 2025/7/22
 **/
public class FileChannelStudy {

    private static final Logger log = LoggerFactory.getLogger(FileChannelStudy.class);

    /**
     * 文件拷贝，是哟 transfer to 的 api 只会传输一次，并不会多次传输数据，所以需要多次传输，他一次传输的上线是 2GB
     *
     * @param inputStream  输入流
     * @param outputStream 输出流
     */
    public void transferTo(final FileInputStream inputStream, final FileOutputStream outputStream) {
        try {
            final FileChannel writeChannel = outputStream.getChannel();
            final FileChannel readChannel = inputStream.getChannel();
            long size = readChannel.size();
            for (long left = size; left > 0; ) {
                left -= writeChannel.transferTo((size - left), left, readChannel);
            }
        } catch (Exception e) {
            log.error("error: {}", e.getMessage(), e);
        }
    }
}
